// 全局变量
let canvas = document.getElementById('drawingCanvas');
let ctx = canvas.getContext('2d');
let isDrawing = false;
let lastX = 0;
let lastY = 0;

// 初始化画布
function initCanvas() {
    ctx.fillStyle = 'white';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.lineWidth = 15;
    ctx.lineCap = 'round';
    ctx.lineJoin = 'round';
}

// 获取鼠标在画布上的位置
function getMousePos(e) {
    const rect = canvas.getBoundingClientRect();
    return {
        x: e.clientX - rect.left,
        y: e.clientY - rect.top
    };
}

// 开始绘制
canvas.addEventListener('mousedown', (e) => {
    isDrawing = true;
    const pos = getMousePos(e);
    lastX = pos.x;
    lastY = pos.y;
});

// 绘制
canvas.addEventListener('mousemove', (e) => {
    if (!isDrawing) return;
    
    const pos = getMousePos(e);
    ctx.beginPath();
    ctx.moveTo(lastX, lastY);
    ctx.lineTo(pos.x, pos.y);
    ctx.stroke();
    
    lastX = pos.x;
    lastY = pos.y;
});

// 停止绘制
canvas.addEventListener('mouseup', () => {
    isDrawing = false;
});

canvas.addEventListener('mouseout', () => {
    isDrawing = false;
});

// 触摸事件支持
canvas.addEventListener('touchstart', (e) => {
    e.preventDefault();
    const touch = e.touches[0];
    const mouseEvent = new MouseEvent('mousedown', {
        clientX: touch.clientX,
        clientY: touch.clientY
    });
    canvas.dispatchEvent(mouseEvent);
});

canvas.addEventListener('touchmove', (e) => {
    e.preventDefault();
    const touch = e.touches[0];
    const mouseEvent = new MouseEvent('mousemove', {
        clientX: touch.clientX,
        clientY: touch.clientY
    });
    canvas.dispatchEvent(mouseEvent);
});

canvas.addEventListener('touchend', (e) => {
    e.preventDefault();
    const mouseEvent = new MouseEvent('mouseup', {});
    canvas.dispatchEvent(mouseEvent);
});

// 清空画布
function clearCanvas() {
    ctx.fillStyle = 'white';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    document.getElementById('predictedDigit').textContent = '?';
    document.getElementById('confidenceBar').style.width = '0%';
    document.getElementById('confidenceText').textContent = '0%';
    document.getElementById('probabilityChart').innerHTML = '';
}

// 获取画布像素数据
function getImageData() {
    // 创建临时画布进行缩放
    const tempCanvas = document.createElement('canvas');
    tempCanvas.width = 28;
    tempCanvas.height = 28;
    const tempCtx = tempCanvas.getContext('2d');
    
    // 将原图缩放到28x28
    tempCtx.drawImage(canvas, 0, 0, 28, 28);
    
    // 获取像素数据
    const imageData = tempCtx.getImageData(0, 0, 28, 28);
    const data = imageData.data;
    
    // 转换为灰度值并归一化
    const pixels = [];
    for (let i = 0; i < data.length; i += 4) {
        const gray = (data[i] + data[i + 1] + data[i + 2]) / 3;
        pixels.push(gray / 255);
    }
    
    return pixels;
}

// 训练模型
async function trainModel() {
    const pixels = getImageData();
    const label = parseInt(document.getElementById('digitLabel').value);
    
    if (isNaN(label) || label < 0 || label > 9) {
        alert('请输入0-9之间的数字标签！');
        return;
    }
    
    try {
        const response = await fetch('/api/train', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                pixels: pixels,
                label: label
            })
        });
        
        const result = await response.json();
        
        if (result.error) {
            alert('训练错误: ' + result.error);
            return;
        }
        
        // 更新状态显示
        document.getElementById('sampleCount').textContent = result.trained_samples;
        
        if (result.status === 'success') {
            document.getElementById('accuracy').textContent = (result.accuracy * 100).toFixed(1) + '%';
            document.getElementById('statusMessage').textContent = result.message;
            
            // 更新进度条
            const progress = Math.min(result.trained_samples * 10, 100);
            document.getElementById('progressBar').style.width = progress + '%';
            document.getElementById('progressBar').textContent = progress + '%';
            
            // 清空画布准备下一张
            clearCanvas();
        } else {
            document.getElementById('statusMessage').textContent = result.message;
        }
        
    } catch (error) {
        console.error('训练失败:', error);
        alert('训练失败，请检查网络连接');
    }
}

// 识别数字
async function predictDigit() {
    const pixels = getImageData();
    
    try {
        const response = await fetch('/api/predict', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                pixels: pixels
            })
        });
        
        const result = await response.json();
        
        if (result.error) {
            alert('识别错误: ' + result.error);
            return;
        }
        
        // 显示预测结果
        document.getElementById('predictedDigit').textContent = result.prediction;
        
        // 显示置信度
        const confidence = Math.round(result.confidence * 100);
        document.getElementById('confidenceBar').style.width = confidence + '%';
        document.getElementById('confidenceText').textContent = confidence + '%';
        
        // 显示概率分布
        displayProbabilities(result.probabilities);
        
    } catch (error) {
        console.error('识别失败:', error);
        alert('识别失败，请检查网络连接');
    }
}

// 显示概率分布
function displayProbabilities(probabilities) {
    const chart = document.getElementById('probabilityChart');
    chart.innerHTML = '';
    
    probabilities.forEach((prob, index) => {
        const percentage = Math.round(prob * 100);
        
        const item = document.createElement('div');
        item.className = 'probability-item';
        
        item.innerHTML = `
            <span class="probability-label">${index}</span>
            <div class="probability-bar">
                <div class="probability-fill" style="width: ${percentage}%"></div>
            </div>
            <span class="probability-value">${percentage}%</span>
        `;
        
        chart.appendChild(item);
    });
}

// 重置模型
async function resetModel() {
    if (!confirm('确定要重置模型吗？这将清除所有训练数据！')) {
        return;
    }
    
    try {
        const response = await fetch('/api/reset', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            }
        });
        
        const result = await response.json();
        
        if (result.status === 'success') {
            document.getElementById('sampleCount').textContent = '0';
            document.getElementById('accuracy').textContent = '-';
            document.getElementById('statusMessage').textContent = '等待训练数据...';
            document.getElementById('progressBar').style.width = '0%';
            document.getElementById('progressBar').textContent = '';
            
            clearCanvas();
            alert('模型已重置！');
        }
        
    } catch (error) {
        console.error('重置失败:', error);
        alert('重置失败，请检查网络连接');
    }
}

// 获取初始状态
async function getStatus() {
    try {
        const response = await fetch('/api/status');
        const result = await response.json();
        
        document.getElementById('sampleCount').textContent = result.trained_samples;
        
        if (result.trained_samples > 0) {
            const progress = Math.min(result.trained_samples * 10, 100);
            document.getElementById('progressBar').style.width = progress + '%';
            document.getElementById('progressBar').textContent = progress + '%';
        }
        
    } catch (error) {
        console.error('获取状态失败:', error);
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    initCanvas();
    getStatus();
});

// 键盘快捷键
document.addEventListener('keydown', (e) => {
    if (e.key === 'c' || e.key === 'C') {
        clearCanvas();
    } else if (e.key === 't' || e.key === 'T') {
        trainModel();
    } else if (e.key === 'p' || e.key === 'P') {
        predictDigit();
    }
});
